package org.openfans.web;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.openfans.domain.Facade;
import org.openfans.domain.Fans;
import org.openfans.domain.RootTag;
import org.openfans.domain.logic.TagRelationManager;
import org.openfans.util.ThreadFans;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

public class RootTagFormController extends SimpleFormController {
	private Facade facade = null;

	public void setFacade(Facade facade) {
		this.facade = facade;
	}

	private TagRelationManager tagRelationManager = null;

	public void setTagRelationManager(TagRelationManager tagRelationManager) {
		this.tagRelationManager = tagRelationManager;
	}

	public RootTagFormController() {
		setCommandName("rootTag");
		setCommandClass(RootTag.class);
	}

	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		RootTag tag = (RootTag) command;
		Fans fans = facade.getFans(ThreadFans.get().getFansId());
		if (request.getParameter("delete") != null) {
			// facade.remove(tag);

		} else {
			facade.saveRootTag(fans, tag);
			facade.digg(tag, fans);
			String rtagTitle = request.getParameter("rtagTitle");
			if (rtagTitle != null && !"".endsWith(rtagTitle)) {
				tagRelationManager.addRelations(tag, rtagTitle);
			}
		}

		return new ModelAndView("redirect:viewTag.html?id=" + tag.getTagId());
	}

	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		ThreadFans.authorize();
		String tagId = request.getParameter("id");

		if ((tagId != null) && !tagId.equals("0")) {
			return (RootTag) facade.getTag(Integer.parseInt(tagId));
		} else {
			String url=request.getParameter("url");
			String descn=request.getParameter("descn");
			String title=request.getParameter("title");
						
			RootTag rootTag = new RootTag();
			rootTag.setTitle(title);
			rootTag.setMainURL(url);
			rootTag.setIntro(descn);
			return rootTag;
		}
	}

	protected Map referenceData(HttpServletRequest request) throws Exception {
		String rtagTitle = request.getParameter("rtagTitle");

		if ((rtagTitle != null) && !rtagTitle.equals("0")) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("rtagTitle", rtagTitle);
			return map;
		}
		return null;
	}
}
